package han.parser;

import han.entity.FinanceProjectInfoEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import static com.han.http.util.Print.printlnInfo;

/**
 * @fileName: FinanceProjectInfoParser
 * @author: Han
 * @date: 2018/6/25 17:30
 * @dscription: 解析从36氪获取的公司信息
 */
public class FinanceProjectInfoParser {

    /**
     * 解析公司描述
     *
     * @param describe 描述json字符串
     */
    public static void setCompanyBasicInfo(String describe, FinanceProjectInfoEntity entity) {
        JSONObject introJson = new JSONObject(describe);
        JSONObject dataJson = introJson.getJSONObject("data");

        //不捕捉异常,如果没有id,直接判断没有该公司记录
        String projectId = dataJson.getInt("id") + "";
        entity.setProjectId(projectId);

        String fullName = "-";
        try {
            fullName = dataJson.getString("fullName");
        } catch (JSONException ignore) {
        }
        entity.setFullName(fullName);
        String cName = "-";
        try {
            cName = dataJson.getString("name");
        } catch (JSONException ignored) {
        }
        entity.setName(cName);
        String webSite = "-";
        try {
            webSite = dataJson.getString("website");
        } catch (JSONException ignore) {
        }
        entity.setWebsite(webSite);
        StringBuilder industrySB = new StringBuilder();
        try {
            //获取标签
            JSONArray industryArray = dataJson.getJSONArray("industryTag");
            for (int i = 0; i < industryArray.length(); i++) {
                String name = industryArray.getJSONObject(i).getString("name");
                industrySB.append(name).append(",");
            }
        } catch (JSONException ignore) {
        }
        entity.setIndustryTag(industrySB.toString());
        //获取概述
        String intro = "-";
        try {
            intro = dataJson.getString("intro");
        } catch (JSONException ignore) {
        }
        entity.setIntro(intro);
        //详细介绍
        String productService = "-";
        String userMarket = "-";
        try {
            JSONObject introduceJson = dataJson.getJSONObject("companyIntroduce");
            productService = introduceJson.getString("productService");
            userMarket = introduceJson.getString("userMarket");
        } catch (JSONException ignore) {
        }
        entity.setProductService(productService);
        entity.setUserMarket(userMarket);
        //一级区域
        String area1 = "-";
        try {
            area1 = dataJson.getString("address1Desc");
        } catch (JSONException ignore) {
        }
        entity.setArea1(area1);
        //二级区域
        String area2 = "-";
        try {
            area2 = dataJson.getString("address2Desc");
        } catch (JSONException ignore) {
        }
        entity.setArea2(area2);
    }

    /**
     * 解析融资经历
     *
     * @param financeRowStr 融资经历json字符串
     */
    public static void setCompanyFinance(String financeRowStr, FinanceProjectInfoEntity entity) {
        JSONObject rowJson = new JSONObject(financeRowStr);
        JSONArray dataArray = rowJson.getJSONArray("data");
        StringBuilder financeSB = new StringBuilder();
        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject tempJson = dataArray.getJSONObject(i);
            String amount = "无";
            try {
                //融资金额
                amount = tempJson.getString("financeAmount");
            } catch (JSONException ignore) {
            }
            String amountUnit = "无";
            try {
                //货币单位
                amountUnit = tempJson.getString("financeAmountUnit");
            } catch (JSONException ignore) {
            }
            Date date = new Date(System.currentTimeMillis());
            try {
                //日期
                long dateL = tempJson.getLong("financeDate");
                date = new Date(dateL);
            } catch (JSONException ignore) {
            }
            String phase = "无";
            try {
                //轮次
                phase = tempJson.getString("phase");
            } catch (JSONException ignore) {
            }
            StringBuilder investSB = new StringBuilder();
            try {
                //投资方
                JSONArray participantArray = tempJson.getJSONArray("participantVos");
                for (int j = 0; j < participantArray.length(); j++) {
                    try {
                        JSONObject tempJsonObj = participantArray.getJSONObject(j);
                        String investName = tempJsonObj.getString("entityName");
                        investSB.append(investName).append(",");
                    } catch (JSONException ignore) {
                    }
                }
            } catch (JSONException e) {
                investSB.append("无");
            }
            financeSB.append("轮次:").append(phase).append(",数额:").append(amount).append(",单位:").append(amountUnit)
                    .append(",投资方:").append(investSB).append(",日期:").append(date).append(";\n");
        }
        entity.setFinanceExperience(financeSB.toString());
    }

    /**
     * 解析创始团队
     *
     * @param memberRowStr 创始团队json字符串
     */
    public static void setCompanyMember(String memberRowStr, FinanceProjectInfoEntity entity) {
        JSONObject rowJson = new JSONObject(memberRowStr);
        JSONObject dataJson = rowJson.getJSONObject("data");
        JSONArray memberArray = dataJson.getJSONArray("members");
        StringBuilder memberSB = new StringBuilder();
        for (int i = 0; i < memberArray.length(); i++) {
            JSONObject tempJson = memberArray.getJSONObject(i);
            //姓名
            String name = "无";
            try {
                name = tempJson.getString("name");
            } catch (JSONException ignore) {
            }
            //职位
            String position = "无";
            try {
                position = tempJson.getString("position");
            } catch (JSONException ignore) {
            }
            //简介
            String intro = "无";
            try {
                intro = tempJson.getString("intro");
            } catch (JSONException ignore) {
            }
            memberSB.append("姓名:").append(name).append(",职位:").append(position).append(",简介:").append(intro)
                    .append(":\n");
        }
        entity.setMember(memberSB.toString());
    }

    /**
     * 解析新闻
     *
     * @param newsRowStr 新闻json字符串
     */
    public static void setCompanyNews(String newsRowStr, FinanceProjectInfoEntity entity) {
        JSONObject rowJson = new JSONObject(newsRowStr);
        JSONArray dataArray = rowJson.getJSONArray("data");
        StringBuilder newsSB = new StringBuilder();
        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject tempJson = dataArray.getJSONObject(i);
            //类型
            String type = "无";
            try {
                type = tempJson.getString("newsType");
            } catch (JSONException ignore) {
            }
            //url
            String url = "无";
            try {
                url = tempJson.getString("newsUrl");
            } catch (JSONException ignore) {
            }
            //日期
            Date date = new Date(System.currentTimeMillis());
            try {
                long dateL = tempJson.getLong("publishDate");
                date = new Date(dateL);
            } catch (JSONException ignore) {
            }
            //来源
            String source = "无";
            try {
                source = tempJson.getString("source");
            } catch (JSONException ignore) {
            }
            //标题
            String title = "无";
            try {
                title = tempJson.getString("title");
            } catch (JSONException ignore) {
            }
            newsSB.append("标题:").append(title).append(",类型:").append(type).append(",源链接:").append(url)
                    .append(",来源:").append(source).append(",日期:").append(date).append(";\n");
        }
        entity.setNews(newsSB.toString());
    }

    public static FinanceProjectInfoEntity getProjectInfoM(String str) {
        //JSON对象
        JSONObject dataJsonObj = new JSONObject(str).getJSONObject("data");

        //融资信息
        StringBuilder financeSB = new StringBuilder();
        try {
            JSONArray financeArray = dataJsonObj.getJSONObject("pastFinance").getJSONArray("data");
            for (int fIndex = 0; fIndex < financeArray.length(); fIndex++) {
                JSONObject tempObj = financeArray.getJSONObject(fIndex);
                //轮次
                String phase = "-";
                try {
                    phase = tempObj.getString("phase");
                } catch (JSONException ignore) {
                }
                //金额
                String amount = "-";
                try {
                    amount = tempObj.getString("financeAmount");
                } catch (JSONException ignore) {
                }
                //估值
                String assert1 = "-";
                try {
                    assert1 = tempObj.getString("asset");
                } catch (JSONException ignore) {
                }
                //融资日期
                String date = "-";
                try {
                    date = tempObj.getString("financeDate");
                } catch (JSONException ignore) {
                }
                //投资机构
                StringBuilder investSB = new StringBuilder();
                try {
                    JSONArray investArray = tempObj.getJSONArray("investEntity");
                    for (int iIndex = 0; iIndex < investArray.length(); iIndex++) {
                        JSONObject investJsonObj = investArray.getJSONObject(iIndex);
                        String investName = "-";
                        try {
                            investName = investJsonObj.getString("name");
                        } catch (JSONException
                                ignore) {
                        }
                        String entityType = "-";
                        try {
                            entityType = investJsonObj.getString("entityType");
                        } catch
                                (JSONException ignore) {
                        }
                        long investId = 0;
                        try {
                            investId = investJsonObj.getLong("id");
                        } catch (JSONException ignore) {
                        }
                        investSB.append("<名称:").append(investName).append(",类型:").append(entityType)
                                .append(",id:").append(investId).append(">,");
                    }
                    financeSB.append("轮次:").append(phase).append(",金额:").append(amount).append(",估值:").append(assert1)
                            .append(",投资方:").append(investSB).append("日期:").append(date).append("\n");
                } catch (JSONException ignore) {
                }
            }
        } catch (JSONException ignore) {
        }

        //成员
        StringBuilder memberSB = new StringBuilder();
        try {
            JSONArray memberArray = dataJsonObj.getJSONObject("member").getJSONArray("data");
            for (int mIndex = 0; mIndex < memberArray.length(); mIndex++) {
                JSONObject tempJsonObj = memberArray.getJSONObject(mIndex);
                long mId = 0;
                try {
                    mId = tempJsonObj.getLong("investorId");
                } catch (JSONException ignore) {
                }
                String mPosition = "-";
                try {
                    mPosition = tempJsonObj.getString("position");
                } catch (JSONException ignore) {
                }
                String mIntro = "-";
                try {
                    mIntro = tempJsonObj.getString("intro");
                } catch (JSONException ignore) {
                }
                try {
                    String mName = tempJsonObj.getString("name");
                    memberSB.append("投资者ID:").append(mId);
                    memberSB.append(",姓名:").append(mName);
                    memberSB.append(",职务:").append(mPosition);
                    memberSB.append(",简介:").append(mIntro).append("\n");
                } catch (JSONException ignore) {
                }
            }
        } catch (JSONException ignore) {
        }

        //报道
        StringBuilder reportSB = new StringBuilder();
        try {
            JSONArray reportArray = dataJsonObj.getJSONObject("report").getJSONArray("data");
            for (int rIndex = 0; rIndex < reportArray.length(); rIndex++) {
                JSONObject tempJsonObj = reportArray.getJSONObject(rIndex);
                long rId = 0;
                try {
                    rId = tempJsonObj.getLong("id");
                } catch (JSONException ignore) {
                }
                String rWebsite = "-";
                try {
                    rWebsite = tempJsonObj.getString("website");
                } catch (JSONException ignore) {
                }
                String rDate = "-";
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    rDate = simpleDateFormat.format(new Date(tempJsonObj.getLong("ts")));
                } catch (JSONException
                        ignore) {
                }
                try {
                    String rTitle = tempJsonObj.getString("title");
                    String rLink = tempJsonObj.getString("link");
                    reportSB.append("id:").append(rId);
                    reportSB.append(",标题:").append(rTitle);
                    reportSB.append(",链接:").append(rLink);
                    reportSB.append(",源站点:").append(rWebsite);
                    reportSB.append(",日期:").append(rDate).append("\n");
                } catch (JSONException ignore) {
                }
            }
        } catch (JSONException ignore) {
        }

        //基础信息
        JSONObject basicJsonObj = dataJsonObj.getJSONObject("basic");
        String name = "-";
        try {
            name = basicJsonObj.getString("name");
        } catch (JSONException ignore) {
        }
        String area1 = "-";
        try {
            area1 = basicJsonObj.getString("address1");
        } catch (JSONException ignore) {
        }
        String area2 = "-";
        try {
            area2 = basicJsonObj.getString("address2");
        } catch (JSONException ignore) {
        }
        long projectId = 0;
        try {
            projectId = basicJsonObj.getLong("ccid");
        } catch (JSONException ignore) {
        }
        //项目信息
        JSONObject projectInfoJsonObj = dataJsonObj.getJSONObject("projectInfo");
        String fullName = "-";
        try {
            fullName = projectInfoJsonObj.getString("fullName");
        } catch (JSONException ignore) {
        }
        String intro = "-";
        try {
            intro = projectInfoJsonObj.getString("intro");
        } catch (JSONException ignore) {
        }
        //联系方式
        String website = "-";
        try {
            JSONObject relatedLink = dataJsonObj.getJSONObject("relatedLink");
            website = relatedLink.getString("website");
        } catch (JSONException ignore) {
        }
        //标签
        StringBuilder tagsSB = new StringBuilder();
        try {
            JSONArray tagsArray = dataJsonObj.getJSONObject("tags").getJSONArray("data");
            for (int tIndex = 0; tIndex < tagsArray.length(); tIndex++) {
                JSONObject tempJsonObj = tagsArray.getJSONObject(tIndex);
                try {
                    String tName = tempJsonObj.getString("name");
                    tagsSB.append(tName).append(",");
                } catch (JSONException ignore) {
                }
            }
        } catch (JSONException ignore) {
        }
        FinanceProjectInfoEntity entity = new FinanceProjectInfoEntity();
        entity.setProjectId(projectId + "");
        entity.setName(name);
        if (fullName.isEmpty()) {
            fullName = "-";
        }
        entity.setFullName(fullName);
        if (website.isEmpty()) {
            website = "-";
        }
        entity.setWebsite(website);
        if (tagsSB.length() == 0) {
            tagsSB = new StringBuilder("-");
        }
        entity.setIndustryTag(tagsSB.toString());
        if (area1.isEmpty()) {
            area1 = "-";
        }
        entity.setArea1(area1);
        if (area2.isEmpty()) {
            area2 = "-";
        }
        entity.setArea2(area2);
        if (intro.isEmpty()) {
            intro = "-";
        }
        entity.setIntro(intro);
        entity.setUserMarket("-");
        entity.setProductService("-");
        if (financeSB.length() == 0) {
            financeSB = new StringBuilder("-");
        }
        entity.setFinanceExperience(financeSB.toString());
        if (reportSB.length() == 0) {
            reportSB = new StringBuilder("-");
        }
        entity.setNews(reportSB.toString());
        if (memberSB.length() == 0) {
            memberSB = new StringBuilder("-");
        }
        entity.setMember(memberSB.toString());
        entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        entity.setPhoneNumber("");
        entity.setAddress("");
        entity.setEmail("");

        return entity;
    }

    public static void main(String... args) {
        printlnInfo(getProjectInfoM("{\"code\":0,\"data\":{\"projectHot\":{\"mc\":\"PROJECT_HOT\",\"canCorrect\":false},\"edit\":{\"editFinance\":\"0\",\"editIndustry\":\"1\",\"level\":\"level3\",\"editHeader\":\"0\",\"editIntro\":\"0\"},\"hasMember\":false,\"investorFocus\":{\"mc\":\"INVESTOR_FOCUS\",\"canCorrect\":false},\"index\":{\"score\":\"0\",\"attentNum\":0,\"hot\":\"0\"},\"pastFinance\":{\"data\":[],\"mc\":\"PAST_FINANCE\",\"canCorrect\":true},\"bp\":{\"mc\":\"BP\",\"canCorrect\":true,\"hasBp\":-1},\"tags\":{\"data\":[{\"name\":\"医疗健康\",\"id\":23,\"hot\":0,\"type\":\"industry1\",\"expose\":1},{\"brief\":\"\",\"uid\":0,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"中医咨讯\",\"industry\":10,\"id\":21954,\"hot\":0,\"type\":\"tag\",\"expose\":1},{\"brief\":\"医疗资讯，指在相对短的时间内，为用户提供医疗健康方面，能够及时地获得、利用并且能够给用户带来价值的信息。\\n资讯有时效性和地域性，它必须被消费者利用。\",\"uid\":702,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"医疗资讯\",\"industry\":10,\"id\":69,\"hot\":0,\"type\":\"tag\",\"expose\":1},{\"brief\":\"媒体是指传播信息的媒介。\\n它是指人借助用来传递信息与获取信息的工具、渠道、载体、中介物或技术手段。\\n也可以把媒体看作为实现信息从信息源传递到受信者的一切技术手段。媒体有两层含义，一是承载信息的物体，二是指储存、呈现、处理、传递信息的实体。\",\"uid\":702,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"媒体\",\"industry\":6,\"id\":58,\"hot\":0,\"type\":\"tag\",\"expose\":1},{\"brief\":\"文化娱乐+媒体\",\"uid\":0,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"文娱传媒\",\"industry\":6,\"id\":7,\"hot\":0,\"type\":\"tag\",\"expose\":1},{\"brief\":\"新闻资讯媒体。\",\"uid\":496,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"新闻资讯\",\"industry\":6,\"id\":6385,\"hot\":0,\"type\":\"tag\",\"expose\":1},{\"brief\":\"专注于某一行业的、能够在相对短的时间内为用户带来价值的信息\",\"uid\":496,\"isDeleted\":0,\"createTime\":1490616825000,\"name\":\"行业资讯\",\"industry\":6,\"id\":407,\"hot\":0,\"type\":\"tag\",\"expose\":1}],\"isMain\":\"1\",\"mc\":\"TAG\",\"canCorrect\":true},\"coreBusiness\":{\"mc\":\"CORE_BUSINESS\",\"canCorrect\":false},\"projectInfo\":{\"mc\":\"INTRO\",\"canCorrect\":true,\"intro\":\"老中医APP是一个中医健康知识资讯平台，专注于为用户提供各种中医养生知识，包括食疗、药膳、药食同源、减肥、健身、保健等相关资料，内容涉及内科、外科、肿瘤和皮肤等医疗领域。\",\"fullName\":\"\"},\"relatedLink\":{\"website\":\"\",\"weixin\":\"\",\"mc\":\"RELATED_LINK\",\"android\":\"\",\"canCorrect\":true,\"iosAppStore\":\"https://itunes.apple.com/cn/app/id1092923505\"},\"similarCompetitor\":{\"totalSimilarCount\":10,\"data\":[{\"brief\":\"中医资讯平台\",\"industry1\":\"医疗健康\",\"funding\":0,\"excellent\":false,\"hasBP\":true,\"pubAt\":0,\"ccid\":88361367,\"name\":\"零点壹网络\",\"logo\":\"http://krplus-pic.b0.upaiyun.com/201803/22/a3298846fbfdb13d60e0a9c6b7a2017f.png\"},{\"brief\":\"中医资讯平台\",\"industry1\":\"医疗健康\",\"funding\":0,\"excellent\":false,\"hasBP\":false,\"pubAt\":0,\"ccid\":22255,\"name\":\"百草中医\",\"logo\":\"https://krplus-pic.b0.upaiyun.com/201508/22225102/6d7058d4ac145e67.png\"},{\"brief\":\"孕婴童健康知识科普平台\",\"industry1\":\"医疗健康\",\"funding\":0,\"excellent\":false,\"hasBP\":false,\"pubAt\":0,\"ccid\":115338,\"name\":\"医知袋鼠\",\"logo\":\"http://krplus-pic.b0.upaiyun.com/201806/08/f09f8f80a0cd69b8ff2c9e6c48205057.png\"},{\"brief\":\"医药资讯平台\",\"industry1\":\"医疗健康\",\"funding\":0,\"excellent\":false,\"hasBP\":false,\"pubAt\":0,\"ccid\":5667,\"name\":\"米内网\",\"logo\":\"https://krplus-pic.b0.upaiyun.com/201511/18/28f4e118c9ff4ed3804a908d28a935a5.jpg\"},{\"brief\":\"医疗美容资讯平台\",\"industry1\":\"医疗健康\",\"funding\":0,\"excellent\":false,\"hasBP\":false,\"pubAt\":0,\"ccid\":134781,\"name\":\"智慧医美圈\",\"logo\":\"https://krplus-pic.b0.upaiyun.com/com_logo_v3/logo_off_134781.jpg\"}],\"mc\":\"SIMILAR_COMPETITOR\",\"more\":true,\"canCorrect\":true},\"contact\":{\"type\":-2},\"extra\":{\"getContactButton\":{\"show\":true,\"type\":1,\"contactUid\":374890971,\"desc\":\"查看联系方式\",\"hasManager\":false},\"workflowStatus\":{\"watched\":false,\"workflowId\":-1}},\"member\":{\"mc\":\"MEMBER\",\"canCorrect\":true},\"report\":{\"mc\":\"REPORT\",\"canCorrect\":true},\"getContactBefore\":false,\"basic\":{\"brief\":\"中医健康知识资讯平台\",\"industry1\":{\"name\":\"MEDICAL_HEALTH\",\"value\":10,\"desc\":\"医疗健康\"},\"funding\":0,\"address2\":\"\",\"address1\":\"北京市\",\"ccid\":100176,\"address1Id\":101,\"address2Id\":0,\"name\":\"老中医APP\",\"logo\":\"https://krplus-pic.b0.upaiyun.com/201603/29/7bb9895bec6f124e3cb981d39c411f56.png\",\"rcid\":204017},\"stock\":{\"basic\":{},\"shareHolder\":{},\"basicLink\":\"\",\"mc\":\"COM_STOCK\",\"canCorrect\":true},\"finance\":{\"chartData\":[],\"financeLink\":\"\",\"mc\":\"COM_FINANCE\",\"canCorrect\":true}},\"msg\":\"操作成功！\"}"));
    }
}
